package com.guanghua.brick.biz;

import java.lang.reflect.Method;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.guanghua.brick.BrickConstant;
import com.guanghua.brick.util.IConfig;

/**
 * weblogic 的ejb locator
 * 
 * @author leeon
 * 
 */
public class WebLogicEJBLocator implements ILocator {
	
	private static final Log logger = LogFactory.getLog(WebLogicEJBLocator.class);

	public Object getBizBean(String id) {
		Properties properties = new Properties();
		try {
			//初始化查找的参数
			InitialContext context = new InitialContext(properties);
			IConfig config = BrickConstant.APP_BIZ_CONTAINER_CONFIG;
			properties.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
			if (config.getText("url") != null)
				properties.put(Context.PROVIDER_URL, config.getText("url"));
	
			if (config.getText("user") != null) {
				properties.put(Context.SECURITY_PRINCIPAL, config.getText("user"));
				properties.put(Context.SECURITY_CREDENTIALS, config.getText("password"));
			}
			
			
			//查找Home接口
			Object ejbObj = context.lookup(id);
			Object objHome = PortableRemoteObject.narrow(ejbObj, ejbObj.getClass());
			
			//调用Home接口create方法
			Class homeClass = objHome.getClass();
			Method homeMethod = homeClass.getDeclaredMethod("create", (Class[])null);
			return homeMethod.invoke(objHome, (Object[])null);
			
		} catch (Exception e) {
			logger.error("failed to create ejb by jndi:" + id, e);
			return null;
		}
	}
}
